package common.util.validator;

import com.alibaba.fastjson.JSONObject;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.exec.RsjIllegalArgueException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 参数转换-校验
 *
 * @author yuanqinglong
 * @since 2021/3/4 14:00
 */
public class ParameterConversionCheck {
    private static final Logger logger = LoggerFactory.getLogger(ParameterConversionCheck.class);

    /**
     * 参数校验和转换
     *
     * @param box        参数
     * @param checkGroup 参数校验组
     * @param target     转换的目标实体
     * @return json参数转为对象
     */
    public static <T> T parameterConversionCheckFastFail(Box box, Class<T> target, Class<?>... checkGroup) {
        MapNode data = box.getMapNode("data");
        T entityParameter = JSONObject.parseObject(JSONObject.toJSONString(data.toMap()), target);
        // 必填参数校验
        String failMessage = ValidatorFactoryUtils.fastFailValidator(entityParameter, checkGroup);
        if (StringUtils.isNotBlank(failMessage)) {
            throw new RsjIllegalArgueException(failMessage);
        }
        return entityParameter;
    }


    /**
     * 参数校验和转换
     *
     * @param box    参数
     * @param target 转换的目标实体
     * @return json参数转为对象
     */
    public static <T> T parameterConversionCheckFastFail(Box box, Class<T> target) {
        MapNode data = box.getMapNode("data");
        T entityParameter;
        try {
            entityParameter = JSONObject.parseObject(JSONObject.toJSONString(data.toMap()), target);
        } catch (Exception e) {
            logger.error("参数序列化异常、参数:{}", box.toJson(), e);
            throw new RsjIllegalArgueException("上传失败、请检查参数格式是否正确");
        }
        // 必填参数校验
        String failMessage = ValidatorFactoryUtils.fastFailValidator(entityParameter);
        if (StringUtils.isNotBlank(failMessage)) {
            throw new RsjIllegalArgueException(failMessage);
        }
        return entityParameter;
    }


    /**
     * 参数转换快速检查失败
     *
     * @param entity 实体
     */
    public static void parameterConversionCheckFastFail(Object entity) {
        // 必填参数校验
        String failMessage = ValidatorFactoryUtils.fastFailValidator(entity);
        if (StringUtils.isNotBlank(failMessage)) {
            throw new RsjIllegalArgueException(failMessage);
        }
    }
}
